#include "staffwin.h"
#include "ui_staffwin.h"
#include "NotificationDialog.h"
#include "sendnotificationdialog.h"
#include <QMainWindow>
#include <QStandardItemModel>
#include <QMessageBox>
#include <QString>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QPushButton>

staffwin::staffwin(QWidget *parent)
    :QMainWindow(parent),
    ui(new Ui::staffwin),
    model(new QStandardItemModel(this)),
    currentPage(1),
    pageSize(10),
    totalItems(0),
    currentTable("abnormalPackages")
    {
    ui->setupUi(this);

    // Setup table view
    ui->ListTable->setModel(model);

    ui->processStorageBtn->setVisible(false);

    // Set window title
    setWindowTitle("物流管理系统 - 员工界面");

    // Setup pagination controls
    setupPagination();

    // Initialize database
    if (!initDatabase()) {
        QMessageBox::critical(this, "数据库错误", "无法连接到数据库");
    }

}



staffwin::~staffwin()
{
    delete ui;
}

void staffwin::setStaffInfo(const QString &username)
{
    ui->StaffNameLine->setText(username);
}

bool staffwin::initDatabase()
{
    sqlDb = QSqlDatabase::addDatabase("QSQLITE");
    sqlDb.setDatabaseName("packages.db");

    if (!sqlDb.open()) {
        QMessageBox::critical(this, "数据库连接错误",
                              "无法打开数据库: " + sqlDb.lastError().text());
        return false;
    }

    return true;
}


// Setup pagination controls
void staffwin::setupPagination()
{
    // Previous page button
    connect(ui->prevPageBtn, &QPushButton::clicked, this, &staffwin::onPrevPageClicked);

    // Page number display and input
    ui->pageSpinBox->setMinimum(1);
    ui->pageSpinBox->setValue(currentPage);
    connect(ui->pageSpinBox, &QSpinBox::valueChanged, this, &staffwin::onPageNumberChanged);

    // Next page button
    connect(ui->nextPageBtn, &QPushButton::clicked, this, &staffwin::onNextPageClicked);

}

// Update pagination controls based on current data
void staffwin::updatePagination()
{
    int totalPages = calculateTotalPages();

    // Update total pages label
    if (ui->totalPagesLabel) {
        ui->totalPagesLabel->setText(QString("/ %1").arg(totalPages));
    }

    // Update spinbox max value
    if (ui->pageSpinBox) {
        ui->pageSpinBox->setMaximum(totalPages > 0 ? totalPages : 1);
        ui->pageSpinBox->setValue(currentPage);
    }

    updatePageNavigationStatus();
}

// Calculate total pages based on item count and page size
int staffwin::calculateTotalPages()
{
    return (totalItems + pageSize - 1) / pageSize;
}

// Update the enabled status of navigation buttons
void staffwin::updatePageNavigationStatus()
{
    int totalPages = calculateTotalPages();

    ui->prevPageBtn->setEnabled(currentPage > 1);
    ui->nextPageBtn->setEnabled(currentPage < totalPages);
}

// Navigation button handlers
void staffwin::onPrevPageClicked()
{
    if (currentPage > 1) {
        currentPage--;

        if (currentTable == "abnormalPackages") {
            loadAbnormalPackagesIntoTable();
        } else if (currentTable == "unsent") {
            loadUnsentPackagesIntoTable();
        } else if (currentTable == "quickInput") {
            loadQuickInputIntoTbale();
        }
    }
}

void staffwin::onNextPageClicked()
{
    int totalPages = calculateTotalPages();
    if (currentPage < totalPages) {
        currentPage++;

        if (currentTable == "abnormalPackages") {
            loadAbnormalPackagesIntoTable();
        } else if (currentTable == "unsent") {
            loadUnsentPackagesIntoTable();
        } else if (currentTable == "quickInput") {
            loadQuickInputIntoTbale();
        }
    }
}

void staffwin::onPageNumberChanged(int page)
{
    if (page != currentPage) {
        currentPage = page;

        if (currentTable == "abnormalPackages") {
            loadAbnormalPackagesIntoTable();
        } else if (currentTable == "unsent") {
            loadUnsentPackagesIntoTable();
        } else if (currentTable == "quickInput") {
            loadQuickInputIntoTbale();
        }
    }
}

void staffwin::loadAbnormalPackagesIntoTable()
{
    ui->processStorageBtn->setVisible(false);

    // Set current table
    currentTable = "abnormalPackages";

    // Clear the model
    model->clear();

    // Set headers
    QStringList headers;
    headers << "订单编号" << "发件人" << "收件人" << "收件人手机号" << "状态" << "取件码";
    model->setHorizontalHeaderLabels(headers);

    // First query to get total count
    QSqlQuery countQuery(sqlDb);
    countQuery.prepare("SELECT COUNT(*) FROM packages WHERE status = 5");

    if (!countQuery.exec()) {
        QMessageBox::warning(this, "查询错误", "获取包裹总数失败: " + countQuery.lastError().text());
        return;
    }

    if (countQuery.next()) {
        totalItems = countQuery.value(0).toInt();
    }

    // Calculate offset based on current page
    int offset = (currentPage - 1) * pageSize;

    // Main query with pagination
    QSqlQuery query(sqlDb);
    query.prepare("SELECT package_id, sender_name, recipient_name, status, claim_code "
                  "FROM packages WHERE status = 5 ORDER BY package_id LIMIT :limit OFFSET :offset");
    query.bindValue(":limit", pageSize);
    query.bindValue(":offset", offset);

    if (!query.exec()) {
        QMessageBox::warning(this, "查询错误", "查询包裹数据失败: " + query.lastError().text());
        return;
    }

    int row = 0;
    while (query.next()) {
        long package_id = query.value(0).toLongLong();
        QString sender = query.value(1).toString();
        QString recipient = query.value(2).toString();
        int status = query.value(3).toInt();
        QString claim_code = query.value(4).toString();

        // Convert status to readable text
        QString statusText;
        switch (status) {
        case 1: statusText = "运输中"; break;
        case 2: statusText = "待入库"; break;
        case 3: statusText = "待取件"; break;
        case 4: statusText = "已取件"; break;
        case 5: statusText = "异常单"; break;
        default: statusText = "未知单"; break;
        }

        // Add data to model
        model->setItem(row, 0, new QStandardItem(QString::number(package_id)));
        model->setItem(row, 1, new QStandardItem(sender));
        model->setItem(row, 2, new QStandardItem(recipient));
        model->setItem(row, 3, new QStandardItem(statusText));
        model->setItem(row, 4, new QStandardItem(claim_code));

        row++;
    }

    // Update pagination controls
    updatePagination();

    ui->ListTable->resizeColumnsToContents();

    if (totalItems == 0) {
        QMessageBox::information(this, "提示", "所有异常单处理完毕！");
    }
}

void staffwin::loadUnsentPackagesIntoTable()
{
    ui->processStorageBtn->setVisible(false);

    // Set current table
    currentTable = "unsent";

    // Clear the model
    model->clear();

    // Set headers
    QStringList headers;
    headers << "订单编号" << "包裹编号" << "收件人" << "收件人地址" << "联系方式" << "状态";
    model->setHorizontalHeaderLabels(headers);

    // First query to get total count
    QSqlQuery countQuery(sqlDb);
    countQuery.prepare("SELECT COUNT(*) FROM orders o JOIN packages p ON o.package_id = p.package_id "
                       "WHERE o.delivery_method = 1 AND p.status < 4"); // Status < 4 means not delivered yet

    if (!countQuery.exec()) {
        QMessageBox::warning(this, "查询错误", "获取未送达包裹总数失败: " + countQuery.lastError().text());
        return;
    }

    if (countQuery.next()) {
        totalItems = countQuery.value(0).toInt();
    }

    // Calculate offset based on current page
    int offset = (currentPage - 1) * pageSize;

    // Main query with pagination
    QSqlQuery query(sqlDb);
    query.prepare("SELECT o.order_id, o.package_id, p.recipient_name, p.recipient_address, "
                  "p.recipient_phone, p.status "
                  "FROM orders o JOIN packages p ON o.package_id = p.package_id "
                  "WHERE o.delivery_method = 1 AND p.status < 4 "
                  "ORDER BY o.order_id LIMIT :limit OFFSET :offset");
    query.bindValue(":limit", pageSize);
    query.bindValue(":offset", offset);

    if (!query.exec()) {
        QMessageBox::warning(this, "查询错误", "查询未送达包裹数据失败: " + query.lastError().text());
        return;
    }

    int row = 0;
    while (query.next()) {
        int order_id = query.value(0).toInt();
        long package_id = query.value(1).toLongLong();
        QString recipient = query.value(2).toString();
        QString address = query.value(3).toString();
        QString phone = query.value(4).toString();
        int status = query.value(5).toInt();

        // Convert status to readable text
        QString statusText;
        switch (status) {
        case 1: statusText = "运输中"; break;
        case 2: statusText = "待入库"; break;
        case 3: statusText = "待取件"; break;
        default: statusText = "未知"; break;
        }

        // Add data to model
        model->setItem(row, 0, new QStandardItem(QString::number(order_id)));
        model->setItem(row, 1, new QStandardItem(QString::number(package_id)));
        model->setItem(row, 2, new QStandardItem(recipient));
        model->setItem(row, 3, new QStandardItem(address));
        model->setItem(row, 4, new QStandardItem(phone));
        model->setItem(row, 5, new QStandardItem(statusText));

        row++;
    }

    // Update pagination controls
    updatePagination();

    ui->ListTable->resizeColumnsToContents();

    if (totalItems == 0) {
        QMessageBox::information(this, "提示", "当前没有待送达的包裹！");
    }
}

void staffwin::loadQuickInputIntoTbale() {
    // Set current table
    currentTable = "quickInput";

    // Clear the model
    model->clear();

    // Set headers
    QStringList headers;
    headers << "选择" << "包裹编号" << "发件人" << "收件人" << "收件人电话" << "取件码";
    model->setHorizontalHeaderLabels(headers);

    // First query to get total count
    QSqlQuery countQuery(sqlDb);
    countQuery.prepare("SELECT COUNT(*) FROM packages WHERE status = 2"); // Status 2 = 待入库

    if (!countQuery.exec()) {
        QMessageBox::warning(this, "查询错误", "获取待入库包裹总数失败: " + countQuery.lastError().text());
        return;
    }

    if (countQuery.next()) {
        totalItems = countQuery.value(0).toInt();
    }

    // Calculate offset based on current page
    int offset = (currentPage - 1) * pageSize;

    // Main query with pagination
    QSqlQuery query(sqlDb);
    query.prepare("SELECT package_id, sender_name, recipient_name, recipient_phone, claim_code "
                  "FROM packages WHERE status = 2 "
                  "ORDER BY package_id LIMIT :limit OFFSET :offset");
    query.bindValue(":limit", pageSize);
    query.bindValue(":offset", offset);

    if (!query.exec()) {
        QMessageBox::warning(this, "查询错误", "查询待入库包裹数据失败: " + query.lastError().text());
        return;
    }

    int row = 0;
    while (query.next()) {
        long package_id = query.value(0).toLongLong();
        QString sender = query.value(1).toString();
        QString recipient = query.value(2).toString();
        QString phone = query.value(3).toString();
        QString claim_code = query.value(4).toString();

        // Create checkbox item
        QStandardItem *checkboxItem = new QStandardItem();
        checkboxItem->setCheckable(true);
        checkboxItem->setCheckState(Qt::Unchecked);

        // Add data to model
        model->setItem(row, 0, checkboxItem);
        model->setItem(row, 1, new QStandardItem(QString::number(package_id)));
        model->setItem(row, 2, new QStandardItem(sender));
        model->setItem(row, 3, new QStandardItem(recipient));
        model->setItem(row, 4, new QStandardItem(phone));
        model->setItem(row, 5, new QStandardItem(claim_code));

        row++;
    }

    ui->processStorageBtn->setVisible(true);

    // Update pagination controls
    updatePagination();

    ui->ListTable->resizeColumnsToContents();

    if (totalItems == 0) {
        QMessageBox::information(this, "提示", "当前没有待入库的包裹！");
    }
}

void staffwin::on_processStorageBtn_clicked()
{
    QList<qlonglong> selectedIds; // Use qlonglong instead of long

    // Collect all checked package IDs
    for (int row = 0; row < model->rowCount(); ++row) {
        QStandardItem *checkItem = model->item(row, 0);
        if (checkItem && checkItem->checkState() == Qt::Checked) {
            qlonglong package_id = model->item(row, 1)->text().toLongLong();
            selectedIds.append(package_id);
        }
    }

    if (selectedIds.isEmpty()) {
        QMessageBox::warning(this, "提示", "请至少选择一个包裹进行处理");
        return;
    }

    // Begin transaction
    sqlDb.transaction();

    bool success = true;
    QSqlQuery updateQuery(sqlDb);
    updateQuery.prepare("UPDATE packages SET status = 3 WHERE package_id = :id");

    QStringList updatedIds;

    foreach (qlonglong id, selectedIds) {
        updateQuery.bindValue(":id", QVariant::fromValue(id));
        if (updateQuery.exec()) {
            // Generate random 6-digit claim code if it doesn't exist
            QSqlQuery checkCodeQuery(sqlDb);
            checkCodeQuery.prepare("SELECT claim_code FROM packages WHERE package_id = :id");
            checkCodeQuery.bindValue(":id", QVariant::fromValue(id));

            if (checkCodeQuery.exec() && checkCodeQuery.next()) {
                QString claimCode = checkCodeQuery.value(0).toString();

                if (claimCode.isEmpty()) {
                    // Generate claim code
                    QString newCode = "123";

                    QSqlQuery addCodeQuery(sqlDb);
                    addCodeQuery.prepare("UPDATE packages SET claim_code = :code WHERE package_id = :id");
                    addCodeQuery.bindValue(":code", newCode);
                    addCodeQuery.bindValue(":id", QVariant::fromValue(id));

                    if (!addCodeQuery.exec()) {
                        success = false;
                        break;
                    }
                }
            }

            updatedIds.append(QString::number(id));
        } else {
            success = false;
            break;
        }
    }

    if (success) {
        sqlDb.commit();
        QMessageBox::information(this, "成功", QString("成功入库 %1 个包裹\n包裹ID: %2")
                                                   .arg(selectedIds.count())
                                                   .arg(updatedIds.join(", ")));

        // Refresh the view
        on_QuickInputStorageBtn_clicked();
    } else {
        sqlDb.rollback();
        QMessageBox::critical(this, "错误", "入库处理失败: " + updateQuery.lastError().text());
    }
}

void staffwin::on_ListAbnormalBtn_clicked()
{
    currentPage = 1;  // Reset to first page when switching tables
    loadAbnormalPackagesIntoTable();
}


void staffwin::on_ListUnsentBtn_clicked()
{
    currentPage = 1;  // Reset to first page when switching tables
    loadUnsentPackagesIntoTable();
}

void staffwin::on_QuickInputStorageBtn_clicked()
{
    currentPage = 1;  // Reset to first page when switching tables
    loadQuickInputIntoTbale();
}



void staffwin::on_ViewNotificationBtn_clicked()
{
    NotificationDialog* dialog = new NotificationDialog(ui->StaffNameLine->text(), this);
    dialog->exec();
}


void staffwin::on_SendNotificationBtn_clicked()
{
    SendNotificationDialog* dialog = new SendNotificationDialog(ui->StaffNameLine->text(), this);
    dialog->exec();
}

